#include "animeview.h"
#include "ui_animeview.h"

#include "flowcontroler.h"

#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QDesktopServices>

AnimeView::AnimeView(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::AnimeView)
{
    ui->setupUi(this);

    connect(ui->labLink, &QLabel::linkActivated, this, [this](const QString & link)
    {
        QDesktopServices::openUrl(QUrl(link));
    });


    connect(FlowControler::Interface, &XInterface::getAllAnimeFinished, this,  [ = ](int ret, QList<Core::Anime> animes)
    {
        if(ret == NoError)
        {
            updateAnimes(animes);
        }
    });
    connect(FlowControler::Interface, &XInterface::getFilterAnimeFinished, this, [ = ](int ret, QList<Core::Anime> animes)
    {
        if(ret == NoError)
        {
            updateAnimes(animes);
        }
    });

    connect(FlowControler::Interface, &XInterface::addAnimeFinished, this,  &AnimeView::animeChanged);
    connect(FlowControler::Interface, &XInterface::deleteAnimeFinished, this,  &AnimeView::animeChanged);
    connect(FlowControler::Interface, &XInterface::updateAnimeFinished, this,  &AnimeView::animeChanged);

    connect(FlowControler::Interface, &XInterface::commentFinished, this,  [ = ](int ret)
    {
        if(ret == NoError)
        {
            ui->lineEdit->clear();
            QMessageBox::information(this, "提示", "评论已发布，等待管理员审核！");
        }
        else
        {
            QMessageBox::warning(this, "警告", "评论发布失败" + FlowControler::Interface->getLastErrorString());
        }
    });

    connect(ui->listWidget, &QListWidget::doubleClicked, this, [ = ](const QModelIndex & index)
    {
        qDebug() << "double clicked";
        m_currentIndex = index.row();
        showAnime(m_animes[m_currentIndex]);
    });
    ui->listWidget->setViewMode(QListWidget::ViewMode::IconMode);
    ui->listWidget->setIconSize(QSize(100, 100));        // 设置图标大小为 64x64 像素
    ui->listWidget->setSpacing(5);

    ui->stackedWidget->setCurrentIndex(0);
}

AnimeView::~AnimeView()
{
    delete ui;
}

void AnimeView::showAnime(Core::Anime &anime)
{
    ui->labName->setText(anime.title);
    ui->labDatetime->setText(anime.releaseDate);
    ui->labTeam->setText(anime.staff);
    ui->labDesc->setText(anime.synopsis);
    ui->labVoice->setText(anime.voiceCast.join(","));

//    ui->labLink->setText(anime.watchLink);
    QString linkText = QString("<a href=\"%1\">%2</a>").arg(anime.watchLink).arg(anime.watchLink);
    ui->labLink->setText(linkText);
    ui->labLink->setTextInteractionFlags(Qt::TextBrowserInteraction);
    ui->labLink->setOpenExternalLinks(true);

    ui->labTag->setText(anime.tags.join(","));

    // 已经评论过的不显示评论框
    bool hasComment = false;
    for(auto c : anime.comments)
    {
        if(c.userId == FlowControler::Interface->getCurrentUser()->id)
        {
            hasComment = true;
            break;
        }
    }

    ui->textEdit->clear();
    for(auto & p : anime.comments)
    {
        QString content = QString("<b style='color:blue;'>%1</b>: %2")
                          .arg(p.userName)
                          .arg(p.content);
        ui->textEdit->append(content);
    }

    ui->widget->setVisible(!hasComment);
    ui->lineEdit->clear();

    ui->stackedWidget->setCurrentIndex(1);
}

void AnimeView::updateAnimes(QList<Core::Anime> animes)
{
    m_animes = animes;

    ui->listWidget->clear();
    for(auto &p : animes)
    {
        QListWidgetItem *item = new QListWidgetItem(p.title);

        QString iconPath = QString(":/res/%1.png").arg(p.title);

        // 检查图标文件是否存在
        if (QFile(iconPath).exists())
        {
            //item->setIcon(QIcon(iconPath)); // 如果文件存在，使用对应的图标
            QPixmap pixmap = QPixmap(iconPath);
            QPixmap scaledPixmap = pixmap.scaled(131, 131, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            QIcon icon(scaledPixmap);
            item->setIcon(icon);
        }
        else
        {
            //item->setIcon(QIcon(":/res/111111111.png")); // 如果文件不存在，使用默认图标
            QPixmap pixmap = QPixmap(":/res/111111111.png");
            QPixmap scaledPixmap = pixmap.scaled(131, 131, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            QIcon icon(scaledPixmap);
            item->setIcon(icon);
        }

        ui->listWidget->addItem(item);
    }


    if(m_currentIndex < animes.size() && ui->stackedWidget->currentIndex() == 1)
    {
        showAnime(animes[m_currentIndex]);

    }
}

void AnimeView::animeChanged(int ret)
{
    if(ret == NoError)
    {
//        FlowControler::Interface->getAllAnimes();
    }
}

void AnimeView::on_pushButton_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void AnimeView::on_btnComment_clicked()
{
    Core::Comment comment;
    comment.userId = FlowControler::Interface->getCurrentUser()->id;
    comment.animeId = m_animes[m_currentIndex].id;
    comment.content = ui->lineEdit->text();

    FlowControler::Interface->commentAnime(comment);
}

void AnimeView::on_btnQuery_clicked()
{
    QString searchText = ui->edit_search->text();
    for (int i = 0; i < ui->listWidget->count(); ++i)
    {
        QListWidgetItem *item = dynamic_cast<QListWidgetItem*>(ui->listWidget->item(i));
        if (searchText.isEmpty())
        {
            item->setHidden(false);
        }
        else
        {
            item->setHidden(!item->text().contains(searchText, Qt::CaseInsensitive));
        }
    }
}
